﻿using CommonLib.LogOperation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using System.Text;

namespace WCFLib.Client
{
    public class ClientHelper
    {
        /// <summary>
        /// 获取客户端IP和端口
        /// </summary>
        public static string GetIPAndPort()
        {
            try
            {
                IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;
                WebHeaderCollection headers = request.Headers;

                if (headers["X-Forwarded-For"] != null)
                    return headers["X-Forwarded-For"];
            }
            catch
            {
                Logger.Error("WebOperationContext获取IP失败");
            }

            OperationContext context = OperationContext.Current;
            MessageProperties properties = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty endpoint = properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            return endpoint.Address + ":" + endpoint.Port;
        }
    }
}
